package dao

import (
	__ "driver_srv/basic/driverproto"
	"driver_srv/handler/models"
	"errors"
	"gorm.io/gorm"
	"time"
)

// 创建线路
func CreateRout(in *__.CreateRouteReq) (*models.Route, error) {
	var err error
	// 查询司机是否存在
	var driver models.Driver
	driver.Id = uint32(in.DriverId)
	if err = driver.FindDriverById(); err != nil {
		return nil, errors.New("查询司机失败")
	}
	if driver.Id == 0 {
		return nil, errors.New("司机不存在")
	}
	// 创建线路
	var router models.Route
	router = models.Route{
		DriverId:   in.DriverId,
		RouteName:  in.RouteName,
		RouteCode:  in.RouteCode,
		StartPoint: in.StartPoint,
		EndPoint:   in.EndPoint,
		RouteTags:  in.RouteTags,
	}
	if err = router.CreateRoute(); err != nil {
		return nil, errors.New("创建线路失败")
	}
	return &router, err
}

// 创建站点
func CreateSite(in *__.CreateSiteReq) (*models.Site, error) {
	var err error
	// 查询线路是否存在
	var route models.Route
	if err = route.GetRouteId(in.RouteId); err != nil {
		return nil, errors.New("查询线路失败")
	}
	if route.Id == 0 {
		return nil, errors.New("线路不存在")
	}
	// 创建站点
	var site models.Site
	site = models.Site{
		SiteCode:   in.SiteCode,
		SiteName:   in.SiteName,
		Longitude:  float64(in.Longitude),
		Latitude:   float64(in.Latitude),
		ArriveTime: int(in.ArrivalTime),
		CreatedAt:  time.Time{},
		UpdatedAt:  time.Time{},
		DeleteTime: gorm.DeletedAt{},
	}
	if err = site.CreateSite(); err != nil {
		return nil, errors.New("创建站点失败")
	}
	return &site, err
}

// 创建站点
func ListSite(in *__.ListSiteReq) ([]*__.ListSite, error) {
	var err error
	// 查询站点列表
	var site models.Site
	listSite, err := site.ListSite()
	if err != nil {
		return nil, errors.New("查询站点列表失败")
	}
	var listSiteList []*__.ListSite
	for _, r := range listSite {
		listSiteList = append(listSiteList, &__.ListSite{
			SiteName:    r.SiteName,
			ArrivalTime: int64(r.ArriveTime),
			RouteName:   r.RouteName,
			RouteCode:   r.RouteCode,
			StartPoint:  r.StartPoint,
			EndPoint:    r.EndPoint,
		})
	}
	return listSiteList, err
}

// 创建用户乘车
func CreateRideRecord(in *__.CreateRideRecordReq) (*models.RideRecord, error) {
	var err error
	//查询用户是否存在
	var user models.User
	if err = user.FindUserById(); err != nil {
		return nil, errors.New("查询用户失败")
	}
	if user.Id == 0 {
		return nil, errors.New("用户不存在")
	}
	// 查询线路是否存在
	var route models.Route
	if err = route.GetRouteId(in.RouteId); err != nil {
		return nil, errors.New("查询线路失败")
	}
	if route.Id == 0 {
		return nil, errors.New("线路不存在")
	}
	// 查询站点是否存在
	var site models.Site
	if err = site.GetSiteId(in.SiteId); err != nil {
		return nil, errors.New("查询站点失败")
	}
	if site.Id == 0 {
		return nil, errors.New("站点不存在")
	}
	var rideRecord models.RideRecord
	rideRecord = models.RideRecord{
		UserId:     in.UserId,
		RouteId:    in.RouteId,
		StartPoint: in.StartPoint,
		EndPoint:   in.EndPoint,
		Status:     in.Status,
	}
	if err = rideRecord.CreateRideRecord(); err != nil {
		return nil, errors.New("创建用户乘车失败")
	}
	return &rideRecord, err
}
